package edu.webtech.project.server.domain;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import edu.webtech.project.server.PMF;
import edu.webtech.project.shared.UserInfoDTO;

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class UserAccount {

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Long id;

	@Persistent
	private String firstName;
	
	@Persistent
	private String lastName;
	
	@Persistent
	private String userName;
	
	@Persistent
	private String userPass;
	
	@Persistent
	private String emailAdd;

	public UserAccount() {}
	
	public UserAccount(String firstName, String lastName, String userName, String userPass, String emailAdd ) {
		this.firstName = firstName;
		this.lastName  = lastName;
		this.userName  = userName;
		this.userPass  = userPass;
		this.emailAdd  = emailAdd;
	}

	public Long getId() {
		return id;
	}
	
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserPass() {
		return userPass;
	}

	public void setUserPass(String userPass) {
		this.userPass = userPass;
	}

	public String getEmailAdd() {
		return emailAdd;
	}

	public void setEmailAdd(String emailAdd) {
		this.emailAdd = emailAdd;
	}
	
	public static UserAccount getDefaultUser(String userName) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		UserAccount oneResult = null, detached = null;
		Query q = pm.newQuery(UserAccount.class, "userName == :name");
		q.setUnique(true);
		try {
			oneResult = (UserAccount) q.execute(userName);
			if (oneResult != null) {
				detached = pm.detachCopy(oneResult);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
			q.closeAll();
		}
		return detached;
	}

	public static UserInfoDTO toDTO(UserAccount user) {
		if (user == null) {
			return null;
		}
		
		return new UserInfoDTO(
				user.getFirstName(),
				user.getLastName(),
				user.getUserName(),
				user.getUserPass(),
				user.getEmailAdd()
				);
	}

}
